//
//  IEAppointCarouselView.m
//  LGIntellectExam
//
//  Created by dangwc on 2019/6/6.
//  Copyright © 2019 dangwc. All rights reserved.
//

#import "IEAppointCarouselView.h"
#import "IEPageControl.h"
#import <AVKit/AVKit.h>
#import <Masonry/Masonry.h>




@interface IEWelcomeModel : NSObject
@property (nonatomic,copy) NSString   *resourcePath;//资源路径
@property (nonatomic,copy) NSString   *title;       //标题
@property (nonatomic,copy) NSString   *subTitle;    //副标题
@end
@implementation IEWelcomeModel
-(instancetype)initWithPath:(NSString *)path
                      title:(NSString *)title
                   subTitle:(NSString *)subTitle{
    if (self = [super init]) {
        _resourcePath = path;
        _title = title;
        _subTitle = subTitle;
        
        
    }
    return self;
}
@end

@interface IEAppointCarouselView()<UIScrollViewDelegate>
@property (nonatomic,strong) UIScrollView *contentView;
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong) IEPageControl *pageControl;
@property (nonatomic,strong) UIButton *nextBtn;
@end

@implementation IEAppointCarouselView

static int i = 0;


-(UIButton *)nextBtn{
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:0];
        
        _nextBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_nextBtn setBackgroundImage:[UIImage imageNamed:@"IEWelcome_nextBtn"] forState:0];
        [_nextBtn setTitleColor:RGBcolor(0, 108, 255) forState:0];
        [_nextBtn setTitle:@"立即体验" forState:0];
        [_nextBtn addTarget:self action:@selector(mainView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}

-(IEPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[IEPageControl alloc] init];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
        _pageControl.hidesForSinglePage = YES;
    }
    return _pageControl;
}


-(UIScrollView *)contentView{
    if (!_contentView) {
        _contentView = [[UIScrollView alloc] init];
        _contentView.delegate = self;
        _contentView.pagingEnabled = YES;
        _contentView.showsHorizontalScrollIndicator = NO;
        _contentView.alwaysBounceHorizontal = YES;
        
    }
    return _contentView;
}

- (instancetype)init{
    if (self = [super init]) {
        [self setupLayout];
        [self setupConstrains];
        NSString *path1 = [[NSBundle mainBundle] pathForResource:@"ai_movie_welcome_0" ofType:@"mp4"];
        NSString *path2 = [[NSBundle mainBundle] pathForResource:@"ai_movie_welcome_1" ofType:@"mp4"];
        NSString *path3 = [[NSBundle mainBundle] pathForResource:@"ai_movie_welcome_2" ofType:@"mp4"];
        NSString *path4 = [[NSBundle mainBundle] pathForResource:@"ai_movie_welcome_3" ofType:@"mp4"];
        IEWelcomeModel *mode_1 = [[IEWelcomeModel alloc] initWithPath:path1 title:@"AI护航   考试常态化" subTitle:@"智能反舞弊 无人监考"];
        IEWelcomeModel *mode_2 = [[IEWelcomeModel alloc] initWithPath:path2 title:@"以考促学   学习效率提高" subTitle:@"三次考试机会  不过再考"];
        IEWelcomeModel *mode_3 = [[IEWelcomeModel alloc] initWithPath:path3 title:@"一键预约   自主掌控" subTitle:@"考试、时间，任你选"];
        IEWelcomeModel *mode_4 = [[IEWelcomeModel alloc] initWithPath:path4 title:@"一键预约   自主掌控" subTitle:@"考试、时间，任你选"];
        self.dataArray = @[mode_1,mode_2,mode_3,mode_4];

        [self reloadData];
        
        self.contentView.contentOffset = CGPointZero;
        if (@available(iOS 11.0, *)) {
            self.contentView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    }
    return self;
}

- (void)setupLayout{
    
    [self addSubview:self.contentView];
    [self addSubview:self.pageControl];
   

}

- (void)setupConstrains{
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(0);
        make.width.mas_equalTo(IE_ScreenWidth);
        make.bottom.mas_equalTo(0);
    }];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(IE_ScreenWidth);
        make.height.mas_equalTo(5);
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(-(IE_SafeAreaBottom + 20));
    }];


}

-(void)reloadData{
    self.contentView.contentSize = CGSizeMake(self.dataArray.count * IE_ScreenWidth,0);
    self.pageControl.numberOfPages = self.dataArray.count;
    CGFloat topHeight = IE_Navigation_height;
    CGFloat videoHeight = IE_ScreenWidth * 0.6 * 1334 / 750;
    
    for (int i=0; i<self.dataArray.count; i++) {
        IEWelcomeModel *model = self.dataArray[i];
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor clearColor];
        videoView.tag = i+100;
        AVPlayerLayer *videoLayer = [[AVPlayerLayer alloc] init];
        videoLayer.frame = CGRectMake(IE_ScreenWidth * 0.4 * 0.5, topHeight, IE_ScreenWidth * 0.6, videoHeight);
        videoLayer.backgroundColor = [UIColor clearColor].CGColor;
        
        
        UILabel *titleLb = [UILabel new];
        titleLb.text = model.title;
        titleLb.textColor = [UIColor blackColor];
        titleLb.font = [UIFont systemFontOfSize:24];
        titleLb.numberOfLines = 0;
        
        UILabel *subTitleLb = [UILabel new];
        subTitleLb.text = model.subTitle;
        subTitleLb.textColor = [UIColor lightGrayColor];
        subTitleLb.font = [UIFont systemFontOfSize:15];
        subTitleLb.numberOfLines = 0;
        [videoView addSubview:titleLb];
        [videoView addSubview:subTitleLb];
        [videoView.layer addSublayer:videoLayer];
        [self.contentView addSubview:videoView];
        [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(IS_IPHONE_5_5S?topHeight+videoHeight+10 : topHeight+videoHeight+30);
            make.centerX.mas_equalTo(0);
        }];

        [subTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(titleLb.mas_bottom).offset(10);
            make.centerX.mas_equalTo(0);
        }];
        
        [videoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.contentView.mas_top);
            make.left.mas_equalTo(i*IE_ScreenWidth);
            make.width.mas_equalTo(IE_ScreenWidth);
            make.height.mas_equalTo(IE_ScreenHeight);
        }];
        AVPlayer *player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:model.resourcePath]];
        videoLayer.player = player;
        [player play];
        
        
        if (i==self.dataArray.count-1) {
            [videoView addSubview:self.nextBtn];
            [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(subTitleLb.mas_bottom).offset(IS_IPHONE_5_5S?10:30);
                make.centerX.mas_equalTo(0);
            }];
        }
    }
    
    if (self.dataArray.count > 1 && self.isAutoScroll) {
        self.isAutoScroll = YES;
    }
    
}


-(void)carouselViewClicked:(UITapGestureRecognizer *)tap{
    if (self.clickedHandle) {
        self.clickedHandle(tap.view.tag);
    }
}


-(void)startGCDTimer{
    __weak typeof(self) weakSelf = self;
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        [weakSelf autoScrollEvent];
    });
    dispatch_resume(timer);
    self.timer = timer;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (i == scrollView.contentOffset.x / IE_ScreenWidth) {
        return;
    }
   i = scrollView.contentOffset.x / IE_ScreenWidth;
   self.pageControl.currentPage = i;
   UIView *currentView = [self.contentView viewWithTag:i+100];
    if (currentView) {
        [currentView.layer.sublayers enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[AVPlayerLayer class]]) {
                AVPlayerLayer *videoLayer = obj;
                [videoLayer.player seekToTime:kCMTimeZero];
                [videoLayer.player play];
            }
        }];
    }
}


-(void)setIsAutoScroll:(BOOL)isAutoScroll{
    _isAutoScroll = isAutoScroll;
    if (_isAutoScroll) {
        [self startGCDTimer];
    }
}

-(void)autoScrollEvent{
    self.pageControl.currentPage = i;
    [self.contentView setContentOffset:CGPointMake(IE_ScreenWidth*i,0) animated:YES];
    i++;
    if (i>self.dataArray.count-1) {
        i=0;
    }
}

-(void)playDidEnd:(NSNotification *)notification{
    
    UIView *currentView = [self.contentView viewWithTag:i+100];
    if (currentView) {
        [currentView.layer.sublayers enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[AVPlayerLayer class]]) {
                AVPlayerLayer *videoLayer = obj;
                if (videoLayer.player.currentItem) {
                    if(CMTimeGetSeconds(videoLayer.player.currentItem.asset.duration) == CMTimeGetSeconds(videoLayer.player.currentItem.currentTime)) {
                        [videoLayer.player.currentItem seekToTime:kCMTimeZero];
                        [videoLayer.player play];
                    }
                }
                }
        }];
    }
}


-(void)mainView{
    if (self.clickedHandle) {
        self.clickedHandle();
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
